// src/pages/catering/orderList/orderList.js
import getIn from '../../../../yali-sdk/utils/getIn';
import orderComfirmQuery from '../../../../yali-sdk/business/catering/orderComfirmQuery.js';
import orderCreatQuery from '../../../../yali-sdk/business/catering/orderCreatQuery.js';
import addressListQuery from '../../../../yali-sdk/business/address/addressListQuery.js';
import { CATERING_ORDER_DETAIL, MEMBER_ADDRESS_LIST_PATH } from '../../../pages/pathUrl';
import { getImagePath, showFail, showSuccess } from '../../../config/common';
import { addNotifier, removeNotifier, notify } from '../../../../yali-sdk/utils/NotifyRegistryCenter';
import { SUCCESS } from '../../../../yali-sdk/utils/success';
import { FAIL } from '../../../../yali-sdk/utils/fail';
import config from '../../../config';
import { wxPay } from '../../../common/wxPayOrder';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showModalStatus: false,
    orderData: {},
    remark: '',
    is_invoice: false,
    table_num: 0, // 用餐人数
    tableWare: 0, // 餐具费总价格
    addressText: '', // 默认地址信息
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const token = getIn(getApp(), ['globalData', 'token']);
    const shop_list = getIn(getApp(), ['globalData', 'shop_list']);
    const shop_id = options.shop_id;
    const color = options.color;
    const template = options.template
    wx.showLoading({ title: '加载中' });
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: color,
    });
    this.setData({ color, template })
    addNotifier && addNotifier('updateProductAddress', (id) => { this.getDefaultAddress(id); }, this);
    global.ActionDispatcher.execute(orderComfirmQuery, { token, shop_id }, (code, res) => {
      if (code == SUCCESS) {
        wx.hideLoading();
        const orderData = res.data;
        const couponList = getIn(res.data, ['coupon_list']);
        let tableWare = 0
        if (couponList.length > 0) {
          const coupon = couponList && couponList.find(x => x.selected == 1);
          orderData.coupon_reduce = coupon.reduce_amount; // 已优惠价格
          orderData.reach_amount = coupon.reach_amount; // 门槛价格
          orderData.face_value = coupon.face_value;
          orderData.discount = coupon.discount;
          orderData.coupon_id = coupon.coupon_id;
          orderData.type = coupon.type; // 优惠券类型
          orderData.member_total = coupon.member_total;
        } 
        if (orderData.tableware_fee && orderData.tableware_fee > 0) {
          tableWare = this.data.table_num * orderData.tableware_fee;
        }
        orderData.member_total = Number(orderData.member_total) + Number(tableWare); // 优惠后价格　＋　餐具费
        orderData.sum_total = Number(orderData.orign_total) + Number(tableWare);
        this.setData({ orderData, shop_id, tableWare, dispatch_fee: orderData.dispatch_fee });
      } else if(code == FAIL) {
        wx.hideLoading();
      }
    });
    this.getDefaultAddress();
  },
  onUnload() {
    removeNotifier('updateProductAddress');
  },
  // 默认地址取值
  getDefaultAddress(id) {
    const token = getIn(getApp(), ['globalData', 'token']);
    let addressDetail = id && this.data.addData && this.data.addData.find(x => x.id == id);
    if (addressDetail) {
      const addressText = addressDetail ? addressDetail.whole_address : '';
      this.setData({ addressText, address_id: id });
    } else {
      global.ActionDispatcher.execute(addressListQuery, { token }, (status, result) => {
        if (status == SUCCESS) {
          const addData = getIn(result, ['data', 'list']);
          if (id) {
            addressDetail = addData && addData.find(x => x.id == id);
          } else {
            addressDetail = addData && addData.find(x => x.is_default == 1);
          }
          const addressText = addressDetail ? addressDetail.whole_address : '';
          const address_id = addressDetail ? addressDetail.id : '';
          this.setData({ addressText, address_id, addData });
        }
      });
    }
  },
  // 弹出优惠券
  onShowCoupon(e) {
    const { orderData } = this.data;
    if (orderData.coupon_list.length > 0) {
      this.setData({ showModalStatus: true });
    }
  },
  /** 关闭优惠券窗口回调* */
  hideCouponCallBack(e) {
    this.setData({
      showModalStatus: getIn(e.detail, ['showModalStatus']),
    });
  },
  // 提交订单
  creatOrder() {
    if (this.data.address_id == '') {
      showFail('请添加地址');
      return false;
    } else {
      const token = getIn(getApp(), ['globalData', 'token']);
      const openid = getIn(getApp(), ['globalData', 'openid']);
      const address_id = getIn(this.data, ['address_id']);
      const params = {
        token,
        shop_id: this.data.shop_id,
        coupon_id: this.data.orderData.coupon_id,
        remark: this.data.remark,
        is_invoice: Number(this.data.is_invoice),
        address_id,
      }
      global.ActionDispatcher.execute(orderCreatQuery, params, (code, res) => {
        if (code == SUCCESS) {
          const order_id = res.data.order_id;
          const pay_way = 2;
          const trade_type = 'JSAPI';
          const domain = getIn(config, ['domain']);
          const queryString = `order_id=${order_id}`;
          const payParams = {
            token, order_id, pay_way, trade_type, domain, openid,
          };
          wxPay(payParams, (status, result) => {
            if (status == SUCCESS) {
              // 通知刷新订单列表
              showSuccess('支付成功');
              notify('GOODS_LIST');
              global.navigateHelper && global.navigateHelper.reLaunch({ pathname: CATERING_ORDER_DETAIL, queryString });
            } else if (status == 'PAY_FAIL') {
              showFail('支付失败');
              notify('GOODS_LIST');
              global.navigateHelper && global.navigateHelper.reLaunch({ pathname: CATERING_ORDER_DETAIL, queryString });
            } else if (status == FAIL) {
              showFail(res && res.msg);
            }
          });
        } else if (code == FAIL) {
          showFail(res.msg)
        }
      });
    }
  },
  // 选择优惠券后产品数据处理
  proData(e) {
    const value = getIn(e.detail, ['value']);
    const key = getIn(e.detail, ['key']);
    const { orderData, tableWare } = this.data;
    const couponList = getIn(orderData, ['coupon_list']);
    const coupon_list = couponList && couponList.map(x => {
      if (x[key] == value) {
        x.selected = true;
        orderData.coupon_reduce = x.reduce_amount;
        orderData.reach_amount = x.reach_amount;
        orderData.face_value = x.face_value;
        orderData.discount = x.discount;
        orderData.member_total = Number(x.member_total) + Number(tableWare);
        orderData.coupon_id = x.coupon_id;
      } else {
        x.selected = false;
      }
      return x;
    });
    orderData.coupon_list = coupon_list;
    this.setData({ orderData });
  },
  // 留言
  onRemark(e) {
    const value = e.detail.value;
    this.setData({ remark: value });
  },
  // 是否需要发票
  onInvoice() {
    this.setData({ is_invoice: !this.data.is_invoice })
  },
  // 用餐人数
  mealNum(e) {
    const value = e.detail.value;
    const { orderData } = this.data;
    const tableWare = orderData.tableware_fee * Number(value);
    const member_total = Number(orderData.member_total) + Number(tableWare); // 优惠后价格　＋　餐具费
    const sum_total = Number(orderData.orign_total) + Number(tableWare);
    this.setData({ 
      table_num: Number(value),
      tableWare,
      'orderData.member_total': member_total,
      'orderData.sum_total': sum_total,
      });
  },
  toAddress() {
    const tag = 1;
    global.navigateHelper && global.navigateHelper.navigateTo({ pathname: MEMBER_ADDRESS_LIST_PATH, queryString: `tag=${tag}`, });
  }
})